package cn.wp.common.core.web;

import cn.hutool.core.util.StrUtil;
import cn.wp.common.core.WpProperties;
import cn.wp.common.core.WpVar;
import cn.wp.common.core.dto.WpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局的的异常处理器
 */
//@Slf4j
//@ControllerAdvice
//@RestControllerAdvice
public class WpGlobalReturnValueAdvice implements ResponseBodyAdvice {

    @Autowired
    private WpProperties wpProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        Class<?> returnType = methodParameter.getMethod().getReturnType();
        // 结果已经为WpResult的跳过
        if(returnType == WpResult.class){
            return false;
        }
        // 结果为ResponseEntity的跳过
        if(returnType == ResponseEntity.class){
            return false;
        }
        // 结果为ModelAndView的跳过
        if(returnType == ModelAndView.class){
            return false;
        }

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String bodyType = WpWebContext.getRequest().getParameter(WpVar.RESPONSE_BODY_TYPE);
        // 从请求头再次获取
        if(StrUtil.isBlank(bodyType)){
            bodyType = WpWebContext.getRequest().getHeader(WpVar.RESPONSE_BODY_TYPE);
        }

        if(StrUtil.isBlank(bodyType)){
            bodyType = WpVar.RESPONSE_JSON_BODY;
        }

        if(bodyType.equals(WpVar.RESPONSE_JSON_BODY)){
            WpResult wpResult = new WpResult().success();
            wpResult.setDataBody(o);
            return wpResult;
        }

        // 返回原始结果
        return o;
    }
}
